(function(){

    var _this = null; 
    function Game(map,obj){
        this.food = new Food();
        this.snake = new Snake();
        this.map = map;
        this.obj = obj;
        this.timer = null;
        _this = this;
    }
    Game.prototype.init = function(){
        this.food.init(this.map);
        this.snake.init(this.map);
        this.runSnake();
        this.bindKey();
    };
    Game.prototype.runSnake = function(obj){
        this.timer = setInterval(function(){
            var headX = this.snake.body[0].x;
            var headY = this.snake.body[0].y;
            var maxX = this.map.offsetWidth / this.snake.width;
            var maxY = this.map.offsetHeight /this.snake.height;
            if(headX > maxX || headX <0 || headY <0 || headY > maxY){
                clearInterval(this.timer);
                alert('游戏结束');
            }
            this.snake.move(this.food,this.map);
            this.score();
        }.bind(_this),100);
    };
    Game.prototype.bindKey = function(e){
        var _this = this;
        window.addEventListener('keydown',function(e){
            switch(e.keyCode){
                case 40: this.snake.direction = 'bottom'; break;
                case 37: this.snake.direction = 'left'; break;
                case 38: this.snake.direction = 'top'; break;
                case 39: this.snake.direction = 'right'; break;
                case 13: 
                    if(this.timer){
                        clearInterval(this.timer);
                        this.timer = null;
                    }else {
                        this.runSnake();
                    }
            }
        }.bind(_this),false);
    };
    Game.prototype.score = function(){
        this.obj.innerHTML = this.snake.scoreFn();
    };
    window.Game = Game;
}());
